package clientserver;

import java.io.IOException;
import java.util.Timer;

import ocsf.server.ConnectionToClient;
import vcp.client.request.Request;
import vcp.client.request.response.ResponseRequest;
import vcp.enums.RequestType;
import vcp.server.DBAdapter;
import vcp.server.VCPServer;
import vcp.server.requesthandler.CancelSubscriptionFormRequestHandler;
import vcp.server.requesthandler.CustomerCheckInRequestHandler;
import vcp.server.requesthandler.CustomerCheckoutRequestHandler;
import vcp.server.requesthandler.CustomerRegularCheckInRequestHandler;
import vcp.server.requesthandler.RequestHandler;
import vcp.server.requesthandler.UserLoginRequestHandler;
import vcp.server.requesthandler.UserLogoutRequestHandler;
import vcp.server.utility.timedecision.TimeDecision;

/**
 * 
 * @author VCP team
 * 
 *         <p>
 *         This class is responsible for providing server services, but acts as
 *         a dummy server. It contains only relevant handlers
 *         </p>
 */
public class DummyServer extends VCPServer
{

	public DummyServer(int port, TimeDecision timeDecision)
	{
		super(port, timeDecision);
		DBAdapter.getAdapter().startDB();
	}

	@Override
	protected void initDeamonList(Timer timerManager, TimeDecision timeDecision)
	{
	}

	@Override
	protected void initHandlersMap()
	{
		this.requestHandlers.put(RequestType.CUSTOMER_CHECK_OUT, new CustomerCheckoutRequestHandler(this));
		this.requestHandlers.put(RequestType.CUSTOMER_CHECK_IN, new CustomerCheckInRequestHandler(this));
		this.requestHandlers.put(RequestType.CUSTOMER_REGULAR_CHECK_IN, new CustomerRegularCheckInRequestHandler(this));
		this.requestHandlers.put(RequestType.USER_LOGIN, new UserLoginRequestHandler(this));
		this.requestHandlers.put(RequestType.USER_LOGOUT, new UserLogoutRequestHandler(this));
		this.requestHandlers.put(RequestType.SUBMIT_CANCEL_FORM, new CancelSubscriptionFormRequestHandler(this));
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void handleMessageFromClient(Object msg, ConnectionToClient client)
	{
		synchronized (this.getDBLock())
		{
			System.out.println("Message received: " + msg + " from " + client);
			if (msg instanceof Request)
			{
				Request request = (Request) msg;

				RequestType commandType = request.getRequest();
				RequestHandler<Request> handler = this.requestHandlers.get(commandType);
				if (handler != null)
				{
					try
					{
						handler.execute(request, client);
					}
					catch (Exception e)
					{
						ResponseRequest responseRequest = new ResponseRequest(request.getRequestID(), null);
						responseRequest.setErrorMessage("Request: " + commandType.toString() + " has crushed on the way to:" + client);
						try
						{
							client.sendToClient(responseRequest);
						}
						catch (IOException ioe)
						{
							ioe.printStackTrace();
						}
						e.printStackTrace();
					}
				}
			}
		}
	}
}
